import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { getUserInfoApi, loginApi, logoutApi } from "@/Api/acl/login";
import { staticRoutes, allAsyncRoutes, anyRoutes } from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";

/**
 * 过滤动态路由表，保留拥有访问权限的路由表
 * @param asyncRoutes 动态路由表
 * @param routes 用户路由权限
 * @returns 拥有访问权限的路由表
 */
const filterRoutes = (asyncRoutes: Array<RouteRecordRaw>, routes: string[]) => {
  return asyncRoutes.filter((asyncRoute) => {
    if (routes.includes(asyncRoute.name as string)) {
      if (asyncRoute.children && asyncRoute.children.length) {
        // const childrenRoutes = filterRoutes(asyncRoute.children, routes);
        // asyncRoute.children = childrenRoutes;
        // 修改了原数据
        asyncRoute.children = filterRoutes(asyncRoute.children, routes);
      }
      return true;
    } else {
      return false;
    }
  });
};

/**
 * 动态添加路由
 * @param hasPermissionRoutes 拥有访问权限的路由表
 */
const addRoutes = (hasPermissionRoutes: Array<RouteRecordRaw>) => {
  // 动态添加路由
  hasPermissionRoutes.forEach((route) => router.addRoute(route));
};

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    routes: [],
    buttons: [],
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      const { token } = await loginApi(username, password);
      // 将token存储起来
      setToken(token); // 将token储存在localStorage中，为了持久化存储
      this.token = token; // 将token存储在pinia中，内存存储，为了读写速度更快
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     if (username === "admin" && password === "111111") {
      //       const token = "token-atguigu";
      //       setToken(token);
      //       this.token = token;
      //       resolve(token);
      //     } else {
      //       reject(new Error("用户名或密码错误!"));
      //       ElMessage.error("用户名或密码错误!");
      //     }
      //   }, 1000);
      // });
    },

    async getInfo() {
      // 发送请求，获取用户数据
      const res = await getUserInfoApi();
      //  存储数据
      this.name = res.name;
      this.avatar = res.avatar;
      this.routes = res.routes;
      this.buttons = res.buttons;

      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     this.name = "admin";
      //     this.avatar =
      //       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
      //     this.menuRoutes = staticRoutes;
      //     resolve({ name: this.name, avatar: this.avatar, token: this.token });
      //   }, 1000);
      // });

      // 动态路由表遍历判断路由有没有权限访问
      // 有权限访问，保留下来
      // 没有权限访问，过滤
      const hasPermissionRoutes = filterRoutes(
        cloneDeep(allAsyncRoutes),
        res.routes
      );

      // 将拥有权限访问的路由表，动态添加到路由中生效，此时就能访问这些路由了
      addRoutes([...hasPermissionRoutes, ...anyRoutes]);

      // 生成左侧菜单
      this.menuRoutes = [...staticRoutes, ...hasPermissionRoutes];
    },
    async logout() {
      await logoutApi(); // 发送请求，删除服务器的token
      this.reset(); // 删除客户端的用户数据
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
      this.routes = [];
      this.buttons = [];
    },
  },
});
